import { vUploadImage,getUploadOssSign,uploadOssFilePath} from '@/api/common'
import axios from 'axios'
import { Message } from 'element-ui'

export function fileUpload(file,group_id=0,path='sys') { // file是文件
    return new Promise((resolve, reject) => {
        // 请求后端签名
        getUploadOssSign({path:path}).then(res => {
            let data = res.data
            let suffix = file.name.split('.')[file.name.split('.').length - 1] // 获取文件后缀

            let filename = new Date().getTime() + Math.floor(Math.random() * 150) +  '.' + suffix

            let formData = new FormData()
            formData.append('key', data.dir + filename ) // 文件名
            formData.append('policy', data.policy) // 后台获取超时时间
            formData.append('OSSAccessKeyId', data.accessid) // 后台获取临时ID
            formData.append('success_action_status', '200') // 让服务端返回200,不然，默认会返回204
            formData.append('signature', data.signature) // 后台获取签名
            formData.append('file', file)
            axios.post(data.host, formData, {
                'Content-Type': 'multipart/form-data'
            }).then(oss_res => {
                console.log(oss_res)
                if (oss_res.status == '200') {
                    Message({
                        message: '上传成功',
                        type: 'success'
                    })
                    let url_file =  data.dir + filename
                    uploadOssFilePath({
                        group_id:group_id,
                        file_size:file.size,
                        file_type:file.type,
                        extension:suffix,
                        host_url: data.cdn_host,
                        file_url:url_file,
                        filename:filename
                    }).then(res =>{
                        console.log('res', res)
                        resolve({url_file:data.host + '/' + data.dir + filename})
                    })


                } else {
                    Message({
                        message: res.message || 'Error',
                        type: 'error'
                    })
                    reject(false)
                }
            })
        })
    })
}

